package com.nami.ucenter.controller.midddleware.mq.consumer;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.json.JSONUtil;
import com.nami.gate.external.basic.constants.UpTopicConst;
import com.nami.gate.external.basic.request.upmsg.LogoutRequest;
import com.nami.gate.external.basic.request.upmsg.client.login.UpMsgLogoutReq;
import com.nami.im.network.model.packet.v2.Packet;
import com.nami.ucenter.facade.logout.request.command.UserLogoutCmd;
import com.nami.ucenter.facade.logout.UserLogoutFacade;
import com.nami.ucenter.controller.convertor.WrapToLogoutCmdAssembler;
import com.nami.transport.utils.MsgTimeUtil;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.rocketmq.spring.annotation.ConsumeMode;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.jetbrains.annotations.Nullable;
import org.springframework.stereotype.Component;


@Slf4j
@Component
@AllArgsConstructor
@RocketMQMessageListener(topic = UpTopicConst.LOGOUT_TOPIC,
    consumerGroup = UpTopicConst.LOGOUT_CONSUMER_GROUP,
    consumeMode = ConsumeMode.CONCURRENTLY)
public class LogoutConsumer implements RocketMQListener<String> {

    private final UserLogoutFacade logoutFacade;

    @Override
    public void onMessage(String body) {
        try {
            TimeInterval timer = DateUtil.timer();
            UserLogoutCmd cmd = parseLogoutMessage(body);
            if (cmd == null || MsgTimeUtil.isMessageExpired(cmd.getCurrTime())) {
                log.warn("[logout] 消息过期，不予处理.  mq消息消费成功！userId={}", cmd.getUserId());
                return;
            }
            logoutFacade.execute(cmd);
            log.info("[logout] logout success use:{}ms", timer.interval());
        } catch (Exception var2) {
            var2.printStackTrace();
            log.error("[logout] logout error", var2);
        }

    }

    private static @Nullable UserLogoutCmd parseLogoutMessage(String body) {
        if (StringUtils.isBlank(body)) {
            log.warn("[logout] message is empty");
            return null;
        }
        final LogoutRequest wrap = JSONUtil.toBean(body, LogoutRequest.class);
        if (wrap == null) {
            log.warn("[logout] message is empty");
            return null;
        }
        Packet packet = wrap.getPacket();
//        final UpMsgLogoutReq request = Serializer.prototype(packet.getSerial()).deserialize(packet.getBody(), UpMsgLogoutReq.class);
        final UpMsgLogoutReq request = new UpMsgLogoutReq();
        return WrapToLogoutCmdAssembler.logoutWrap2UserLogoutCmd(wrap, request);
    }


}
